/**
 * @file rscNet.c
 * @brief Short description of this file.
 *
 * Complete description of this file.
 *
 * @date Mar 27, 2012
 * @author Francesco Corvino
 */
#include "rscNet.h"


int RscNet_CmpOperations(const void * a, const void * b){
	int A,B;
	if((a==NULL) && (b==NULL)) return 0;
	if(a!=NULL) A = ((NetOperation*) a)->nsequence; else return -1;
	if(b!=NULL) B = ((NetOperation*) b)->nsequence; else return 1;
	return (A>B)?1:((A==B)?0:-1);
}

void RscNet_init(HostSession * session){
	// inizializza i dati sulle operazioni di rete della sessione
	NetSession netSession;
	DynArray_init(&(netSession.operations), RscNet_CmpOperations,sizeof(NetOperation));

	// salva in memoria della sessione l'oggetto
	CMap_set(&(session->attributes), KEY_NETINFO_INT, &netSession, sizeof(NetSession));
}

void RscNet_addOperation(HostSession * session, NetOperation * op){

}

void PAddress_initS(PAddress * a, char *name, char *port){
	memset(a,0,sizeof(PAddress));
	if((a->address= malloc(strlen(name)+1))!=NULL){
		strcpy(a->address,name);
	}
	a->port = atoi(port);
}

void PAddress_init(Address * addr, PAddress * paddr){
	paddr->family = addr->sa_family;
    switch(addr->sa_family) {
        case AF_INET:
        	if((paddr->address = malloc(INET_ADDRSTRLEN))!=NULL) {
        		struct sockaddr_in * cadd = (struct sockaddr_in *) addr;
                inet_ntop(AF_INET, &(cadd->sin_addr), paddr->address, INET_ADDRSTRLEN);
                paddr->port = htons(cadd->sin_port);
        	}
            break;
        case AF_INET6:
        	if((paddr->address = malloc(INET6_ADDRSTRLEN))!=NULL){
        		struct sockaddr_in6 * cadd = (struct sockaddr_in6 *)addr;
                inet_ntop(AF_INET6, &(cadd->sin6_addr), paddr->address,INET6_ADDRSTRLEN);
                paddr->port = htons(cadd->sin6_port);
        	}
            break;
        default:
        	paddr->port = 0;
        	paddr->address = NULL;
        	break;
    }
}

void PAddress_destory(PAddress *paddr){
	if(paddr->address!=NULL) free(paddr->address);
	paddr->address = NULL;
}

void PAddress_get(PAddress *p,Address *a){
	p->family = (p->address[0]==':')?AF_INET6:AF_INET;
	if(inet_pton(p->family, p->address, a)!=-1){
		return;
	}
}
